package com.lancoo.klgcourseware.manager;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static android.media.MediaPlayer.MEDIA_INFO_BUFFERING_END;
import static android.media.MediaPlayer.MEDIA_INFO_BUFFERING_START;

public class KlgLocalMediaManager {

    private MediaPlayer mMediaPlayer;
    private boolean isPause,isPrepared,isStoped;
    private OnPlayListener mListener;
    private Context mContext;
    protected Toast mToast;
    private AlertDialog vipPayForDialog;
    private long time;
    private ExecutorService mSingleExecutor;
    private volatile boolean mIsSeekComplete = true;

    public KlgLocalMediaManager(){
//        mToast = Toast.makeText(mContext, null,Toast.LENGTH_SHORT);
        mSingleExecutor = Executors.newSingleThreadExecutor();
    }
    public KlgLocalMediaManager(Context mContext){
        this.mContext=mContext;
        mToast = Toast.makeText(mContext, "", Toast.LENGTH_SHORT);
        mSingleExecutor = Executors.newSingleThreadExecutor();
    }

    public void setUpMedia(final String filePath, final OnPlayListener listener) {
        isPause=false;
        isStoped=false;
        mListener = listener;
        if(TextUtils.isEmpty(filePath)){
            mListener.onSourceError();
            return;
        }
        if (null == mMediaPlayer) {
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
                @Override
                public void onBufferingUpdate(MediaPlayer mp, int percent) {
                    if (listener != null) {
                        listener.onBufferingUpdate(mp, percent);
                    }
                }
            });
            mMediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                @Override
                public void onSeekComplete(MediaPlayer mp) {
                    mIsSeekComplete = true;
                }
            });
            mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {

                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
//                    mMediaPlayer.stop();
                    mMediaPlayer.reset();
                    if (listener != null&&!isStoped) {
                        listener.onStartError();
//                        mToast.show();
                    }
                    return true;
                }
            });
            mMediaPlayer.setOnInfoListener(mOnInfoListener);
        } else {
//            mMediaPlayer.stop();
            mMediaPlayer.reset();

        }

        isPrepared=false;
        mMediaPlayer.setAudioStreamType(android.media.AudioManager.STREAM_MUSIC);
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (null != listener) {
                    listener.onComplete();
                }
//                isPrepared=false;
            }
        });
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    mMediaPlayer.setDataSource(filePath);
                    mMediaPlayer.prepareAsync();
                } catch (IOException e) {
                    e.printStackTrace();

                    if (listener != null) {
                        listener.onSourceError();
//                mToast.show();
                    }
                }
            }
        }.start();
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                isPrepared=true;
                if (listener != null&&!isPause) {
                    listener.onPrepare();
                }

            }
        });
    }


    public void setUpMedia(AssetFileDescriptor fileDescriptor, final OnPlayListener listener) {
        isPause=false;
        isStoped=false;
        mListener = listener;
        if(fileDescriptor==null){
            mListener.onSourceError();
            return;
        }
        if (null == mMediaPlayer) {
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
                @Override
                public void onBufferingUpdate(MediaPlayer mp, int percent) {
                    if (listener != null) {
                        listener.onBufferingUpdate(mp, percent);
                    }
                }
            });
            mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {

                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
//                    mMediaPlayer.stop();
                    mMediaPlayer.reset();
                    if (listener != null&&!isStoped) {
                        listener.onStartError();
//                        mToast.show();
                    }
                    return true;
                }
            });
        } else {
//            mMediaPlayer.stop();
            mMediaPlayer.reset();

        }

        isPrepared=false;
        mMediaPlayer.setAudioStreamType(android.media.AudioManager.STREAM_MUSIC);
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (null != listener) {
                    listener.onComplete();
                }
//                isPrepared=false;
            }
        });
        try {
            mMediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),fileDescriptor.getStartOffset(),fileDescriptor.getLength());
            if(mMediaPlayer!=null){
                mMediaPlayer.prepareAsync();
            }


        } catch (Exception e) {
            e.printStackTrace();
            if (listener != null) {
                listener.onSourceError();
//                mToast.show();
            }
        }
        if(mMediaPlayer!=null){
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    isPrepared=true;
                    if (listener != null&&!isPause) {
                        listener.onPrepare();
                    }

                }
            });
        }

    }

    public void start() {
        if (null != mMediaPlayer&&isPrepared) {
            isPause=false;
            mSingleExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    mMediaPlayer.start();
                }
            });
        }

    }

    private long mLastBufferingStartTime = -1;
    private MediaPlayer.OnInfoListener mOnInfoListener = new MediaPlayer.OnInfoListener() {
        @Override
        public boolean onInfo(MediaPlayer mp, int what, int extra) {
            if (what == MEDIA_INFO_BUFFERING_START){
                mLastBufferingStartTime = System.currentTimeMillis();
            }else if (what == MEDIA_INFO_BUFFERING_END){
                mLastBufferingStartTime = -1;
            }
            return true;
        }
    };


    public void pause() {
        isPause = true;
//        if (null != mMediaPlayer ) {
        if (null != mMediaPlayer && mMediaPlayer.isPlaying()) {
            mSingleExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    mMediaPlayer.pause();
                }
            });
            if (null != mListener) {
                mListener.onPausePlay();
            }
        }
    }

    public void resume() {
        if (null != mMediaPlayer && isPause) {
            mMediaPlayer.start();
            isPause = false;
            if (null != mListener) {
                mListener.onResumePlay();
            }
        }
    }

    public void release() {
        if (mSingleExecutor!=null
                && !mSingleExecutor.isShutdown()){
            mSingleExecutor.shutdownNow();
            mSingleExecutor = null;
        }
        if (null != mMediaPlayer) {
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
            }
            isPause = false;
            mMediaPlayer.release();
            mMediaPlayer = null;
//            mToast.cancel();
        }
    }

    public void stop() {
        if (null != mMediaPlayer) {
            isStoped=true;
            mMediaPlayer.stop();
            isPause = false;
            isPrepared=false;
            if (null != mListener) {
                mListener.onStopPlay();
            }
        }
    }

    public void seekTo(final int msec) {
        mSingleExecutor.execute(new Runnable() {
            @Override
            public void run() {
                if (mMediaPlayer != null&&isPrepared) {
                    mIsSeekComplete = false;
                    mMediaPlayer.seekTo(msec);
                }
            }
        });
    }

    public boolean isPause() {
        return isPause;
    }
    public boolean isPrepared() {
        return isPrepared;
    }


    public boolean isPlay() {
        if (mMediaPlayer != null) {
            return mMediaPlayer.isPlaying();
        }
        return false;
    }

    public int getDuring() {
        if (mMediaPlayer != null && isPrepared) {
            return mMediaPlayer.getDuration();
        }

        return 0;
    }

    public int getCurrentPosition() {
        if (mMediaPlayer != null && isPrepared) {
            return mMediaPlayer.getCurrentPosition();
        }
        return 0;
    }

    public interface OnPlayListener {
        void onComplete();

        void onStartError();

        void onPausePlay();

        void onSourceError();

        void onResumePlay();

        void onStopPlay();

        void onPrepare();

        void onBufferingUpdate(MediaPlayer mp, int percent);

    }

    public void changePlaySpeed(final float speed){
        if(Build.VERSION.SDK_INT> Build.VERSION_CODES.N&&isPrepared){
            try{
                mSingleExecutor.execute(new Runnable() {
                    @Override
                    public void run() throws IllegalStateException {
                        long time = System.currentTimeMillis();
                        if (mIsSeekComplete)
                            mMediaPlayer.setPlaybackParams(mMediaPlayer.getPlaybackParams().setSpeed(speed));
                    }
                });

            }catch (Exception e){
                Log.e("aaaa","IllegalStateException:"+e.toString());
            }

        }
    }

}